package com.fjh.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fjh.constant.SysUserConstant;
import com.fjh.domain.SysUserRole;
import com.fjh.mapper.SysUserRoleMapper;
import com.fjh.service.SysUserRoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.data.domain.Page;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.Serializable;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fjh.mapper.SysUserMapper;
import com.fjh.domain.SysUser;
import com.fjh.service.SysUserService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

@Service
@Slf4j
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService{
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private SysUserRoleService sysUserRoleService;


    /**
     *
     * @param id
     * @return
     */
    @Override
    public SysUser getById(Serializable id) {
        log.info("查询当前登录的用户身份信息，id为{}", id);
        String sysUserStr = redisTemplate.opsForValue().get(SysUserConstant.SYS_USER_PREFIX + id);
        SysUser sysUser = null;
        if (StringUtils.hasText(sysUserStr)){
            sysUser = JSON.parseObject(sysUserStr,SysUser.class);
        }else {
            sysUser = sysUserMapper.selectById(id);
            if (!ObjectUtils.isEmpty(sysUser)){
                redisTemplate.opsForValue().set(SysUserConstant.SYS_USER_PREFIX + id, JSON.toJSONString(sysUser), Duration.ofDays(7));
            }
        }
        return sysUser;

    }

    /**
     * 新增用户
     * @param sysUser
     * @return
     */
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public boolean save(SysUser sysUser) {
        log.info("新增用户{}", JSON.toJSONString(sysUser));
        sysUser.setCreateTime(new Date());
        sysUser.setShopId(1L);
        String password = sysUser.getPassword();
        //对密码进行加密
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(password);
        sysUser.setPassword(encode);
        int i = sysUserMapper.insert(sysUser);
        if (i > 0) {
            List<Long> roleIdList = sysUser.getRoleIdList();
            List<SysUserRole> sysUserRoles = new ArrayList<>(roleIdList.size());
            roleIdList.forEach(rId -> {
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setRoleId(rId);
                sysUserRole.setUserId(sysUser.getUserId());
                sysUserRoles.add(sysUserRole);
                // 可以使用mybatis的批量操作  我也可以在xml 写 <foreach    >
                sysUserRoleService.saveBatch(sysUserRoles);
            });
        }
        return i > 0;
    }

    /**
     * 分页查询管理员列表
     * @param page
     * @param sysUser
     * @return
     */
    @Override
    public Page<SysUser> loadSysUserPage(Page<SysUser> page, SysUser sysUser) {
        return sysUserMapper.selectPage(page, new LambdaQueryWrapper<SysUser>()
                .like(StringUtils.hasText(sysUser.getUsername()), SysUser::getUsername, sysUser.getUsername())
                .orderByDesc(SysUser::getCreateTime));
    }

}
